package services;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.ParticipantRepository;
import security.LoginService;
import security.UserAccount;
import domain.Event;
import domain.Participant;
import forms.ParticipantForm;

@Service
@Transactional
public class ParticipantService {
	// Managed repository -----------------------------------------------------
	@Autowired
	private Md5PasswordEncoder encoder;
	
	@Autowired
	private ParticipantRepository participantRepository;
	
	// Constructors -----------------------------------------------------------
	
	public ParticipantService(){
		super();
	}
	
	// Simple CRUD methods ----------------------------------------------------
	
	public Participant create() {
		return new Participant();
	}

	public void save(Participant p) {
		Assert.notNull(p);
		if(p.getId()==0)
		p.getUserAccount().setPassword(encoder.encodePassword(p.getUserAccount().getPassword(),null));
		participantRepository.save(p);
	}
	
	// Other business methods -------------------------------------------------
	
	public Participant findByPrincipal() {
		UserAccount u = LoginService.getPrincipal();
		Participant p = participantRepository.findByUserAccountId(u.getId());
		return p;
	}
	
	public Collection<Participant> findParticipantsByEvent(Event event){
		Collection<Participant> participants = participantRepository.findParticipantsByEvent(event.getId());
		return participants;
	}
	
	// Form related methods ----------------------------------------------------
	public ParticipantForm getFormObject(Participant participant){
		ParticipantForm res;
		
		res = new ParticipantForm();
		res.setCreditCard(participant.getCreditCard());
		res.setEmail(participant.getEmail());
		res.setId(participant.getId());
		res.setName(participant.getName());
		res.setSurname(participant.getSurname());
		res.setUserAccount(participant.getUserAccount());
		res.setVersion(participant.getVersion());
		
		return res;
	}
	
	public Participant reconstruct(ParticipantForm participantForm){
		Participant res;
		
		if(participantForm.getId()!=0)
			res = participantRepository.findOne(participantForm.getId());
		else
			res = create();
		
		res.setCreditCard(participantForm.getCreditCard());
		res.setEmail(participantForm.getEmail());
		res.setId(participantForm.getId());
		res.setName(participantForm.getName());
		res.setSurname(participantForm.getSurname());
		res.setUserAccount(participantForm.getUserAccount());
		res.setVersion(participantForm.getVersion());
		
		return res;
	}
}
